const Router = require("koa-router");
const router = new Router();
const KoaConfig = require("../../../koaconfig");
const { getAuthorInfoById, addAuthor } = require("../../db/DBApi/AuthorApi");
const { hashPassword, comparePassword } = require("../../utils/bcryptTool");
const {
  getToken,
  getLongToken,
  getShortToken,
} = require("../../utils/tokenTool");
const fs = require("fs");
const path = require("path");

router.prefix(KoaConfig.path.public);

// 登录页面
// 前端提供用户名和密码，后端验证通过后返回token
router.post("/login", async (ctx, next) => {
  const { email, password } = ctx.request.body;
  const res = await getAuthorInfoById(email);

  if (!res) {
    ctx.status = 404;
    ctx.body = {
      code: 404,
      message: "用户不存在或者密码错误",
    };
    return;
  }

  // 验证密码
  const isMatch = await comparePassword(password, res.password);
  if (!isMatch) {
    ctx.status = 404;
    ctx.body = {
      code: 404,
      message: "用户不存在或者密码错误",
    };
    console.log("密码错误");
    return;
  }

  // 生成token
  // const token = getToken({ email: email });
  const shortToken = getShortToken({ email: email });
  const loginToken = getLongToken({ email: email });

  // 返回token
  ctx.status = 200;
  ctx.body = {
    code: 200,
    message: "登录成功",
    data: {
      // token: token,
      shortToken: shortToken,
      loginToken: loginToken,
    },
  };
});

// 注册页面
router.post("/register", async (ctx, next) => {
  const { email, nickname, password, description, createdTime } =
    ctx.request.body;

  // 验证邮箱格式
  const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailReg.test(email)) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: "邮箱格式错误",
    };
    return;
  }

  // 验证邮箱是否已注册
  try {
    const res = await getAuthorInfoById(email);
    if (res) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: "邮箱已注册",
      };
      return;
    }

    // 加密密码
    const hashedPassword = await hashPassword(password);

    // 创建作者对象
    const authorInfo = {
      email: email,
      nickname: nickname || "",
      password: hashedPassword,
      avatar: "",
      description: description || "",
      createdTime: createdTime || new Date(),
    };

    // 新增作者信息
    const author = await addAuthor(authorInfo);

    // 新增作者信息相关的目录
    // 新增头像目录
    // 同步创建目录
    fs.mkdirSync(
      path.join(__dirname, "../../../public/author", email, "/avatar"),
      { recursive: true }
    );
    // 新增文章目录
    fs.mkdirSync(
      path.join(__dirname, "../../../public/author", email, "/articles"),
      { recursive: true }
    );

    // 判断作者是否新增成功
    if (!author) {
      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: "注册失败",
      };
      return;
    }

    // 返回注册成功信息
    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: "注册成功",
    };
  } catch (err) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "注册失败",
    };
  }
});

module.exports = router;
